import React from 'react';
import classnames from 'classnames';
import { inject } from 'mobx-react';

import { getTreeDataUrl } from '../apis/card';
import List from './list';
import Tree from './tree';
import Card from './card';
import Reply from './reply'
import cubeMind from './cubeMind'
import ViewCustomPage from './custompage'
import CodeViewer from '../pages/bar-code';
import NoRightPage from '../pages/no-right';
import { MapViewer } from '../pages/map'
import { WeaPopoverHrm, WeaErrorPage,WeaLocaleProvider } from 'ecCom';
import equals from 'deep-equal';
import LogList from "../pages/log-list";
import ViewResource from "../pages/view-resource";
import _ from 'lodash';
import { TreeStore } from '../stores/tree'
import { listStore } from '../stores/list';
import ReplyStore from '../stores/reply';
import CardStore from '../stores/card';
import { CustomPageStore } from '../stores/custompage';
import { message } from 'antd';
import TemplateManage from '../pages/templateManage';
import Board from './board';
import Timeline from './timeline';
import MindMap from './mindMap';
import jQuery from "jquery";
import {BatchPrint} from './list/BatchPrint';
const getLabel = WeaLocaleProvider.getLabel;
export interface DockerProps {
    prefixCls?: string;
    className?: string;
    params?: any;
    BarCodeStore: any;
    QrCodeStore: any;
    Tree: any;
    Search: any;
    location?: any;
    cubeLogList: any;
    customPageStore: any;
    mapPage: any;
    BatchPrint:any;
}
export interface UrlDockerStore {
    url: string;
    prefixCls?: string;
    className?: string;
    Tree: TreeStore;
    Search: listStore;
    Reply: ReplyStore;
    Card?: CardStore;
    ViewCustomPage:CustomPageStore;
}
export class UrlDocker extends React.Component<UrlDockerStore, any> {
    componentWillMount() {
        this.props.url && this.doUpdate(this.props.url);
    }
    componentWillReceiveProps(nextProps) {
        if (this.props.url != nextProps.url) {
            this.doUpdate(nextProps.url);
        }
    }
    getGuid = (href: string = '') => {
        const [url] = href.split('?');
        if (url.startsWith("/spa/cube/index.html")||url.startsWith("/spa/cube/index.jsp")) {
            if (url.endsWith("card")) {
                return "card";
            } else if (url.endsWith("search")) {
                return 'search';
            } else if (url.endsWith("tree")) {
                return 'tree';
            } else if (url.endsWith("reply")) {
                return 'reply';
            }else if(url.endsWith("viewCustomPage")){
                return "viewCustomPage";
            }else if(url.endsWith("BatchPrint")){
                return "BatchPrint";
            }
        }
        return '';
    }
    getQuery = (href: string) => {
        const lastofnum = href.lastIndexOf('?');
         href = href.slice(lastofnum);
        const query = href.split('?')[1];
        const querys = query ? query.split("&") : [];
        const queryObj: any = {};
        querys.map(q => {
            const index = q.indexOf("=");
            const name = q.substring(0, index);
            const value = q.substring(index + 1);
            _.set(queryObj, name, value);
        });
        _.set(queryObj, 'guid', this.getGuid(href));
        return queryObj;
    }
    doUpdate = (url) => {
        const query = this.getQuery(url);
        const guid = this.getGuid(url);
        const store = _.get(this.props, guid.charAt(0).toUpperCase() + guid.slice(1));
        if (store) {
            if(guid == 'search'){
                store.updateParams({...query,t:new Date().getTime()},true);
                return;
            }
            store.updateParams(query,true);
        }
    }

    componentWillUnmount(){
        jQuery("#custompageCodeArea").html("");
        jQuery("#cubelistCodeArea").html('');
    }
    render() {
        const { prefixCls = 'coms-mode-docker', className } = this.props;
        const guid = this.getGuid(this.props.url);
        const Com = { search: List, tree: Tree, card: Card, reply: Reply ,viewCustomPage:ViewCustomPage}[guid];
        const classNames = classnames(className, prefixCls, `coms-mode-${guid}`);
        return (
            <div className={classNames}>
                {window.location.href.indexOf('/spa/cube/index.html') > -1 ? <WeaPopoverHrm /> : <div />}
                {Com && <CubeErrorPage><Com {...this.props} /></CubeErrorPage>}
                {/* {Com && <Com {...this.props} />} */}
                <div id="custompageCodeArea" style={{display:"none"}}></div>
                <div id="cubelistCodeArea" style={{display:"none"}}></div>
            </div>
        )
    }
}

const getQuery = (href: string) => {
    const lastofnum = href.lastIndexOf('?');
    href = href.slice(lastofnum);
    const query = href.split('?')[1];
    const querys = query ? query.split("&") : [];
    const queryObj: any = {};
    querys.map(q => {
        const index = q.indexOf("=");
        const name = q.substring(0, index);
        const value = q.substring(index + 1);
        _.set(queryObj, name, value);
    });
    return queryObj;
}
@inject('Search', 'Tree', 'BarCodeStore', 'QrCodeStore', 'Card', 'reply',  'cubeLogList','cubeViewResource',"mapStore",'customPageStore','BatchPrint')
export default class Docker extends React.Component<DockerProps, any> {
    componentWillMount() {
        this.doUpdate(this.props);
    }
    componentWillReceiveProps(nextProps) {
        let nextP = nextProps.location.action;
        let thisP = this.props.location;
        delete nextP.action;
        delete thisP.action;
        if (!equals(nextP, thisP)) {
            this.doUpdate(nextProps);
        }
    }
    doUpdate = (props) => {
        const { location, params, Search, Tree, BarCodeStore, QrCodeStore, Card, reply, cubeLogList ,cubeViewResource,mapStore,customPageStore,BatchPrint } = props;
        const query = getQuery(decodeURI(window.location.href));	//这里不要使用location.search，问题见#608611
        if (params.guid == 'anyurl') {
            getTreeDataUrl(query).then(({ status, error, errorCode, href }) => {
                if (status == '1') {
                    window.location.href = href;
                } else {
                    message.error(`[${getLabel(127353, "错误")+errorCode}]:${error}`);
                    window.location.href = '/spa/cube/index.html#/main/cube/nofound';
                }
            });
            return;
        }

        const store = { search: Search, tree: Tree, barCode: BarCodeStore, qrCode: QrCodeStore, card: Card, reply, logList: cubeLogList,viewResource:cubeViewResource,map:mapStore,viewCustomPage: customPageStore,BatchPrint:BatchPrint }[params.guid];
        if (store && store.updateParams) {
            store.updateParams({ ...query, ...params, _key: location.key });
        }
    }
    componentWillUnmount(){
        jQuery("#custompageCodeArea").html("");
        jQuery("#cubelistCodeArea").html('');
    }
    render() {
        if(window.location.href.indexOf('/main/cube/cubeMind')>0){
            window.location.href=window.location.href.replace('cubeMind','mindMap')+'&isold=1';
            return <div></div>
        }
        const { prefixCls = 'coms-mode-docker', className, params } = this.props;
        const Com = {
            search: List, tree: Tree, card: Card, barCode: CodeViewer,
            noright: NoRightPage, qrCode: CodeViewer, map: MapViewer, reply: Reply,
             logList: LogList,viewResource:ViewResource
            , viewCustomPage: ViewCustomPage,templateManage:TemplateManage, cubeMind: cubeMind,board:Board,mindMap:MindMap,
            BatchPrint:BatchPrint,timeline:Timeline
        }[params.guid];
        const classNames = classnames(className, prefixCls,`coms-mode-${params.guid}`);
        const printClassNames =classnames(className, `cube-card-wrap`);
        const props = { location: this.props.location } as any;
        if (params.guid == 'barCode') {
            props.CodeStore = this.props.BarCodeStore;
        } else if (params.guid == 'qrCode') {
            props.CodeStore = this.props.QrCodeStore;
        }else if (params.guid == 'BatchPrint') {
            props.BatchPrintStore = this.props.BatchPrint;
        }
        return (
            <div className={params.guid == 'BatchPrint'?printClassNames:classNames}>
                {window.location.href.indexOf('/spa/cube/index.html') > -1 || window.location.href.indexOf('/spa/cube/index.jsp') > -1  ? <WeaPopoverHrm /> : <div />}
                {Com && <CubeErrorPage><Com {...props} /></CubeErrorPage>}
                {/* {Com && <Com {...props} />} */}
                <div id="custompageCodeArea" style={{display:"none"}}></div>
                <div id="cubelistCodeArea" style={{display:"none"}}></div>
            </div>
        )
    }
}

class CubeErrorPage extends React.Component<any,any>{
    constructor(props){
        super(props);
        this.state = {isError:false}
    }
    componentDidCatch(error,info){
        this.setState({
            isError:true,
        });
    }
    render(){ 
        if(this.state.isError){
            return <WeaErrorPage msg={ getLabel(383324, "对不起，该页面异常，请联系管理员")} />
        }else{
            return this.props.children
        }
    }
}
